package com.etone.web.controller.task;

import com.alibaba.fastjson2.JSONObject;
import com.etone.common.core.domain.AjaxResult;
import com.etone.common.core.domain.entity.SysDictData;
import com.etone.common.utils.DateUtils;
import com.etone.common.utils.StringUtils;
import com.etone.common.utils.http.HttpUtils;
import com.etone.system.domain.*;
import com.etone.system.mapper.*;
import com.etone.system.service.*;
import com.etone.system.service.impl.AgvServiceImpl;
import com.etone.web.controller.system.AgvController;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 定时任务调度测试
 *
 * @author etone
 */
@Component("ryTask")
public class RyTask
{
    @Autowired
    private ISixFreetaskService sixFreetaskService;

    @Autowired
    private ISysDibiaoService sysDibiaoService;

    @Autowired
    private IFiveTaskinfoService fiveTaskinfoService;

    @Autowired
    private ITurnoverInventoryMapper iTurnoverInventoryMapper;

    @Autowired
    private FiveTaskinfoMapper fiveTaskinfoMapper;

    @Autowired
    private SysDibiaoMapper dibiaoMapper;

    @Autowired
    private AgvMapper agvMapper;

    @Autowired
    private SysStorageMapper sysStorageMapper;

    @Autowired
    private FiveCtuRecordMapper fiveCtuRecordMapper;

    @Autowired
    private SixWuliaoinfoMapper sixWuliaoinfoMapper;

    @Autowired
    private SixFreetaskMapper sixFreetaskMapper;

    @Autowired
    private ISixWuliaoinfoService sixWuliaoinfoService;

    @Autowired
    private AgvService agvService;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private ITurnoverInventoryService turnoverInventoryservice;

    @Autowired
    private ISysStorageService sysStorageService;

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
    {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params)
    {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams() {
        //获取所有的待执行的工作任务，定时查询所要执行的任务终点位置是否有空位置释放，如果检索到则立即执行相应任务，
        //任务执行结束之后，将该任务从待执行任务表中删除
        SixFreetask sixFreetask = new SixFreetask();
        sixFreetask.setTasking("0");
        List<SixFreetask> list = sixFreetaskService.selectSixFreetaskList(sixFreetask);
        if (list.size()!=0){
            for (SixFreetask sixFreetask1 : list){
                String type = sixFreetask1.getType();
                String taskModelType = sixFreetask1.getTaskModeltype();
                if (type.equals("3")) {
                    //首先判断是否有空位置释放
                    Long endp = Long.parseLong(sixFreetask1.getEndp());
                    SysDibiao sysDibiao = new SysDibiao();
                    sysDibiao.setType(endp);
                    List<SysDibiao> dibiaos = sysDibiaoService.selectSysFreeDibiaoList(sysDibiao);
                    if (dibiaos.size() != 0) {
                        //说明有空闲位置
                        Long startp = Long.parseLong(sixFreetask1.getStartp());
                        String huojia = sixFreetask1.getHuojia();
                        String startText = sixFreetask1.getStartText();
                        String endText = sixFreetask1.getEndText();
                        Map<String, Object> map = AgvController.operateFreeHuojia(taskModelType, startp, endp, huojia,
                                startText, endText, sysDibiaoService, fiveTaskinfoService, sixFreetaskService);
                        String status = map.get("code").toString();
                        if (status.equals("200")) {
                            sixFreetask1.setTasking("1");
                            sixFreetaskService.updateSixFreetask(sixFreetask1);
                        }
                    }
                } else if (type.equals("0") | type.equals("2")) {
                    //首先判断是否有空位置释放
                    List<SysDibiao> dibiaos = null;
                    SysDibiao sysDibiao = new SysDibiao();
                    if (type.equals("0")) {
                        sysDibiao.setType(2l);
                    } else if (type.equals("2")) {
                        sysDibiao.setType(4l);
                    }
                    dibiaos = sysDibiaoService.selectSysFreeDibiaoList(sysDibiao);
                    if (dibiaos.size() != 0) {
                        String wuliaoinfo = sixFreetask1.getWuliaoInfo();
                        Gson gson = new Gson();
                        List<TurnoverInventory> list1 = Arrays.asList(gson.fromJson(wuliaoinfo, TurnoverInventory[].class));
                        AjaxResult ajaxResult = AgvServiceImpl.callAgv(list1, type, fiveTaskinfoMapper, dibiaoMapper, agvMapper, sysStorageMapper,
                                fiveCtuRecordMapper, sixWuliaoinfoMapper, iTurnoverInventoryMapper, sixFreetaskMapper);
                        String status = ajaxResult.get("code").toString();
                        if (status.equals("200")) {
                            sixFreetask1.setTasking("1");
                            sixFreetaskService.updateSixFreetask(sixFreetask1);
                        }
                    }
                } else if (type.equals("4")) {
                    //判断地标上是否有空货架释放
                    Long endp = Long.parseLong(sixFreetask1.getEndp());
                    SysDibiao sysDibiao = new SysDibiao();
                    sysDibiao.setType(endp);
                    List<SysDibiao> dibiaos = sysDibiaoService.selectSysFreeDibiaoList(sysDibiao);
                    if (dibiaos.size() != 0) {
                        //说明有空闲位置
                        Long startp = Long.parseLong(sixFreetask1.getStartp());
                        //判断startp是否有空闲货架了
                        String freehuojia = gainFreeHuojia(startp);
                        if(!freehuojia.equals("")){
                            //                        String huojia = sixFreetask1.getHuojia();
                            String startText = sixFreetask1.getStartText();
                            String endText = sixFreetask1.getEndText();
                            Map<String, Object> map = AgvController.operateFreeHuojia(taskModelType, startp, endp, freehuojia,
                                    startText, endText, sysDibiaoService, fiveTaskinfoService, sixFreetaskService);
                            String status = map.get("code").toString();
                            if (status.equals("200")) {
                                sixFreetask1.setTasking("1");
                                sixFreetaskService.updateSixFreetask(sixFreetask1);
                            }
                        }
                    }
                }else if(type.equals("1")){
                    SysStorage sysStorage = new SysStorage();
                    sysStorage.setIsFree(0l);
                    sysStorage.setIsRequest(0l);
                    List<Map<String,Object>> storages = sysStorageService.selectSysStorageList(sysStorage);
                    if(storages.size()!=0){
                        String wuliaoinfo = sixFreetask1.getWuliaoInfo();
                        String huojia = sixFreetask1.getHuojia();
                        String atr = sixFreetask1.getStartp();
                        Gson gson = new Gson();
                        List<TurnoverInventory> list1 = Arrays.asList(gson.fromJson(wuliaoinfo, TurnoverInventory[].class));
                        agvService.callRCTUAgv(type,taskModelType,list1,huojia,atr);
                        sixFreetask1.setTasking("1");
                        sixFreetaskService.updateSixFreetask(sixFreetask1);
                    }
                }else if(type.equals("5")){
                    //查询是否有要到达结束时间的需要清空的出库位货架，自动实现整货架清空功能,要注意的是对出库位上的货架执行清空功能，
                    //如果记录中该货架已经被搬离出库位则不予处理
                    //获取货架编号
                    String huojiaNo = sixFreetask1.getHuojia();
                    //判断货架位置
                    SysDibiao sysDibiao = new SysDibiao();
                    sysDibiao.setHuojia(huojiaNo);
                    List<SysDibiao> dibiaos = dibiaoMapper.selectSysDibiaoList(sysDibiao);
                    if(dibiaos.size()!=0){
                        SysDibiao dibiao = dibiaos.get(0);
                        String dibiaoType = dibiao.getType().toString();
                        if(dibiaoType.equals("4")){//说明货架在出库位
                            //获取此记录的创建时间
                            long createTime = sixFreetask1.getCreateTime().getTime();
                            //获取处理时间
                            List<SysDictData> datas = dictDataMapper.selectDictDataByType("huojia_waittime");
                            long timeVal = Integer.parseInt(datas.get(0).getDictValue())*60*1000;
                            long solveTime = createTime+timeVal;
                            //获取当前时间
                            long currtime = DateUtils.getNowDate().getTime();
                            //获取当前时间，对比记录的创建时间+10分钟与当前时间，如果当前时间大于前值，则执行此货架的清空功能
                            if(currtime >= solveTime){
                                SysStorage sysStorage = new SysStorage();
                                sysStorage.setLieType(huojiaNo);
                                List<Map<String,Object>> lists = sysStorageMapper.selectSysStorageList(sysStorage);
                                if(lists.size()!=0){
                                    for(Map<String,Object> map1 : lists){
                                        String aa = gainStr(map1.get("cangweiNo").toString());
                                        System.out.println("仓位解绑接口返回值======="+aa);
                                    }
                                    //将货架关联的物料信息清空，物料溯源结束
                                    sixWuliaoinfoMapper.deleteSixWuliaoinfoByhuojiacode(huojiaNo);
                                    //将出库货架所有关联货位状态为free
                                    bindcangweiornobind(huojiaNo, 0, 0);
                                    sixFreetask1.setTasking("1");
                                    sixFreetaskService.updateSixFreetask(sixFreetask1);
                                }
                            }
                        }else{
                            sixFreetask1.setTasking("1");
                            sixFreetaskService.updateSixFreetask(sixFreetask1);
                        }
                    }

                }else if(type.equals("6")){
//                    SysDibiao sysDibiao =  new SysDibiao();
//                    sysDibiao.setType(3l);
//                    List<SysDibiao> dblists = dibiaoMapper.selectSysNotFreeDibiaoList1(sysDibiao);
//                    if(dblists.size()!=0){
//                        String wuliaoinfo = sixFreetask1.getWuliaoInfo();
//                        Gson gson = new Gson();
//                        List<TurnoverInventory> list1 = Arrays.asList(gson.fromJson(wuliaoinfo,
//                                TurnoverInventory[].class));
//                        Map<String, Object> map =turnoverInventoryservice.addTurnoverOutbound(list1);
//                        String status = map.get("code").toString();
//                        if (status.equals("200")) {
//                            sixFreetask1.setTasking("1");
//                            sixFreetaskService.updateSixFreetask(sixFreetask1);
//                        }
//                    }
                }
            }
        }
    }
    private static String rcsUrl = "http://172.16.0.200:8182/rcms/services/rest/hikRpcService/";
    public static String gainStr(String cangweino){
        String response = "";
        String param = "{\n" +
                "    \"reqCode\": \"\",\n" +
                "    \"reqTime\": \"\",\n" +
                "    \"clientCode\": \"\",\n" +
                "    \"tokenCode\": \"\",\n" +
                "    \"ctnrTyp\": \"1\",\n" +
                "    \"ctnrCode\": \"\",\n" +
                "    \"wbCode\": \"\",\n" +
                "    \"podCode\": \"\",\n" +
                "    \"podDir\": \"\",\n" +
                "    \"podTyp\": \"\",\n" +
                "    \"materialLot\": \"\",\n" +
                "    \"agvCode\": \"\",\n" +
                "    \"taskCode\": \"\",\n" +
                "    \"stgBinCode\": \""+cangweino+"\",\n" +
                "    \"indBind\": \"0\",\n" +
                "    \"data\": \"\"\n" +
                "}";
        JSONObject json = JSONObject.parseObject(param);
        String reqCode = UUID.randomUUID().toString().substring(0, 20);
        json.fluentPut("reqCode", reqCode);
        json.fluentPut("reqTime", DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));
        json.fluentPut("taskCode", reqCode);
        response = HttpUtils.sendRestPost(rcsUrl+"bindCtnrAndBin",json);
        return response;
    }
    public void bindcangweiornobind(String position, long isrequest, long isfree) {
        SysStorage sysStorage = new SysStorage();
        sysStorage.setLieType(position);
        List<Map<String, Object>> list = sysStorageMapper.selectSysStorageList(sysStorage);
        for (Map<String, Object> map : list) {
            sysStorage.setCangweiNo(null);
            sysStorage.setId(Long.parseLong(map.get("id").toString()));
            sysStorage.setIsRequest(isrequest);
            sysStorage.setIsFree(isfree);
            sysStorageMapper.updateSysStorage(sysStorage);
        }
    }
    public String gainFreeHuojia(long type){
        String freehuojia = "";
        SysDibiao sysDibiao = new SysDibiao();
        sysDibiao.setType(type);
        List<SysDibiao> dibiaos = sysDibiaoService.selectSysDibiaoList(sysDibiao);
        for(SysDibiao sysDibiao1 : dibiaos){
            String huojia1 = sysDibiao1.getHuojia();
            if(huojia1!=null){
                //判断是否是空货架
                SixWuliaoinfo sixWuliaoinfo = new SixWuliaoinfo();
                sixWuliaoinfo.setHuojiaCode(huojia1);
                List<SixWuliaoinfo> list2 =
                        sixWuliaoinfoService.selectSixWuliaoinfoList(sixWuliaoinfo);
                if(list2.size()==0){
                    freehuojia = huojia1;
                    break;
                }
            }
        }
        return freehuojia;
    }
}
